package com.sanerzone.smscenter.api.util;

import com.google.common.collect.Lists;
import com.sanerzone.smscenter.account.service.impl.AccountServiceImpl;
import com.sanerzone.smscenter.api.entity.ApiResult;
import com.sanerzone.smscenter.api.entity.ProcessResult;
import com.sanerzone.smscenter.api.http.SmsApiTemplateController;
import com.sanerzone.smscenter.biz.VerifyInterface.data.ResultData;
import com.sanerzone.smscenter.biz.VerifyInterface.data.Sort;
import com.sanerzone.smscenter.biz.cache.*;
import com.sanerzone.smscenter.biz.entity.SmsPhoneWhiteList;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSWLMessage;
import com.sanerzone.smscenter.biz.utils.StringHelper;
import com.sanerzone.smscenter.common.tools.JedisUtils;
import com.sanerzone.smscenter.common.tools.MQHelper;
import com.sanerzone.smscenter.common.tools.ValidateHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.text.SimpleDateFormat;
import java.util.*;
@Service
public class InterfaceUtil {

    private Logger logger = LoggerFactory.getLogger(InterfaceUtil.class);


    @Autowired
    private  MQHelper mqHelper;
    /**
     * 用户发送限制处理
     * 规则:非行业用户一天最多发5次，一次最多发一条，进入待审核
     * @param pMap
     */
    public static ProcessResult userSendLimitProcess(Map pMap,List<String> phones){

        String userId = StringHelper.valueof( pMap.get( "userid" ) );
//        String appid = StringHelper.valueof( pMap.get( "appid" ) );
//        String key = userId + "_" + appid;
//        String accountGroupId = AccountCacheHelper.getStringValue( key, "groupId", "" );
//        //非行业用户

        if (phones.size() >= SmsApiTemplateController.MINSEND_NUM && phones.size() < SmsApiTemplateController.MINSEND_NUM) {
            return new ProcessResult( 0 );
        }
        if (phones.size() <= SmsApiTemplateController.MAXTEXTSEND_NUM) {//测试
            String num = JedisUtils.get( userId );
            if (num == null) {
                JedisUtils.set( userId, "0", 86400 );
                num = 0 + "";
            }
            int todayTimes = Integer.parseInt( num );//今天已发次数
            todayTimes++;
            if (todayTimes > 5) {//超过发送次数
                return new ProcessResult( 0 );
            }
            JedisUtils.update(userId,todayTimes+"" );

        }

        return new ProcessResult( 1 );
    }


    public static boolean isToday(Date date) {
        //当前时间
        Date now = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
        //获取今天的日期
        String nowDay = sf.format(now);
        //对比的时间
        String day = sf.format(date);

        return day.equals(nowDay);



    }

    public void verifyWhiteList(String phone,String accountGroupId,String userId,String content){
        if (!accountGroupId.equals( "30" )){
            return ;
        }

        Jedis jedis=null;

        String matchMinSizeStr=null;     //单次发送量不超过这个数量，就收集
        String matchMinArea=null;       //号码数量地区不超过这个数量的地区  就按照不超过条数收集
        String eachAreaMinNum=null;     //在每个地区下不超过这个条数，就全部手机
        String maxRepeatNum=null;       //收集的最大重复条数
        String minContentSize=null;     //短信字数
        String maxPhoneSizeByContent=null;//在不超过 minContentSize 的字数下，最大手机的号码数量
        //获取数据
        try{
            jedis=JedisUtils.getResource();
            matchMinSizeStr=jedis.get( "matchMinSize" );
            matchMinArea=jedis.get( "matchMinArea" );
            eachAreaMinNum=jedis.get( "eachAreaMinNum" );
            maxRepeatNum=jedis.get( "maxRepeatNum" );
            minContentSize=jedis.get( "minContentSize" );
            maxPhoneSizeByContent=jedis.get( "maxPhoneSizeByContent" );
            if (matchMinSizeStr==null){
                matchMinSizeStr="1";
                jedis.set( "matchMinSize",matchMinSizeStr );
            }
            if (matchMinArea==null){
                matchMinArea="5";
                jedis.set( "matchMinArea",matchMinArea );
            }
            if (eachAreaMinNum==null){
                eachAreaMinNum="20";
                jedis.set( "eachAreaMinNum",eachAreaMinNum );
            }
            if (maxRepeatNum==null){
                maxRepeatNum="100";
                jedis.set( "maxRepeatNum",maxRepeatNum );
            }
            if (minContentSize==null){
                minContentSize="10";
                jedis.set( "minContentSize",minContentSize );
            }
            if (maxPhoneSizeByContent==null){
                maxPhoneSizeByContent="20";
                jedis.set( "maxPhoneSizeByContent",maxPhoneSizeByContent );
            }

        }catch (Exception e){
            matchMinSizeStr="1";
            matchMinArea="5";
            eachAreaMinNum="20";
            maxRepeatNum="100";
            minContentSize="10";
            maxPhoneSizeByContent="20";
            logger.error( "获取缓存错误" );
        }finally {
            if (jedis!=null){
                jedis.close();
            }
        }
        int matchMinSize=Integer.parseInt( matchMinSizeStr );
        int matchMinAreaInt= Integer.parseInt( matchMinArea );
        int eachAreaMinNumInt= Integer.parseInt( eachAreaMinNum );
        int maxRepeatNumInt= Integer.parseInt( maxRepeatNum );
        int minContentSizeInt=Integer.parseInt( minContentSize );
        int maxPhoneSizeByContentInt=Integer.parseInt( maxPhoneSizeByContent );

        //如果只有一条，加入白名单
        Map<String,SmsPhoneWhiteList> whiteList=new HashMap( );
        String[] phones=phone.split( "," );

        if (phones.length<=matchMinSize){
            for (int i=0;i<phones.length;i++){
                whiteList.put(phones[i], new SmsPhoneWhiteList( phones[i],"系统检测添加:发送条数小于",userId ) );

            }
        }else if (content.length()<=minContentSizeInt&&phones.length<=maxPhoneSizeByContentInt){
            //内容过短:不超过10个字 号码少于20个  全都收集
            for (int i=0;i<phones.length;i++){
                whiteList.put( phones[i],new SmsPhoneWhiteList( phones[i],"系统检测添加:内容过短:不超过"+minContentSizeInt+"个字且号码少于"+maxPhoneSizeByContentInt+"个",userId ) );
            }
        }
        //替所有的手机号码按照地区分组 再判断有哪些是重复的号码
        Map<String,Sort> sorts=new HashMap<>( );
        List<String> repeatPhone=new ArrayList<>( );
        String phoneAfterReplace=phone;
        for (int i=0;i<phones.length;i++){
            String phoneTemp=phones[i];
            Map<String,String> map=PhoneHelper.get( phoneTemp );
            String cityCode=PhoneHelper.getCityCode(map);
            Sort sort=sorts.get( cityCode );
            if (sort==null){
                sorts.put( cityCode,new Sort(new StringBuffer( phoneTemp )  ) );
            }else{
                sort.getSb().append( ","+phoneTemp );
            }
            String phoneAfterChange= phone.replace( phoneTemp,"" );
            if ((phoneAfterChange.length()-phoneAfterReplace.length())>15){
                //说明有重复
                repeatPhone.add( phoneTemp );
                phoneAfterReplace=phoneAfterChange;
            }
        }
        if (sorts.size()<=matchMinAreaInt){
            Set<String> cityCodes=sorts.keySet();
            Iterator<String> iterator=cityCodes.iterator();
            while(iterator.hasNext()){
                String tempKey=iterator.next();
                Sort sort=sorts.get( tempKey );
                String phone1=sort.getSb().toString();
                String[] phones1=phone1.split( "," );
                if (phone1.length()<=eachAreaMinNumInt){
                    for (int i=0;i<phones1.length;i++){
                        whiteList.put( phones1[i],new SmsPhoneWhiteList( phones[i],"系统检测添加:地区不超过"+matchMinArea+"个,号码不超过"+eachAreaMinNum+"个",userId ) );
                    }
                }
            }
        }
        int num=0;
        //再把重复的号码放入whiteList中 单词添加不超过100个
        for(String temp:repeatPhone){
            whiteList.put( temp,new SmsPhoneWhiteList( temp,"系统检测添加:重复号码,单词添加不超过"+maxRepeatNumInt+"个",userId )  );
            num++;
            if (num>=maxRepeatNumInt){
                break;
            }
        }
        //判断whiteList哪些号码是数据库里没有的 直接在缓存里做判断

        Set<String> phoneSet = whiteList.keySet();
        Iterator<String> phoneIterator = phoneSet.iterator();
        while (phoneIterator.hasNext()) {
            String phoneT = phoneIterator.next();
            if (WhitelistHelper.isExist( phoneT )) {
                //如果已经存在  剔除
                whiteList.remove( phoneT );
            }else{
                //如果不存在 加入缓存中 并发送mq
                WhitelistHelper.put( phoneT );
                SmsPhoneWhiteList smsPhoneWhiteList= whiteList.get( phoneT );
                SMSWLMessage smswlMessage=new SMSWLMessage();
                BeanUtils.copyProperties( smsPhoneWhiteList,smswlMessage );
                mqHelper.sendWL( smswlMessage );
            }
        }
    }




}
